<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    <el-form-item label="title" prop="title">
      <el-input v-model="ruleForm.title" autocomplete="off" />
    </el-form-item>
    <el-form-item label="content" prop="content">
      <el-input v-model.number="ruleForm.content" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >Submit</el-button
      >
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { FormInstance } from "element-plus";
import { addArtcle, editArtcile, getArticleDetail } from "./service";

const route = useRoute();
const router = useRouter();

const ruleFormRef = ref<FormInstance>();

const ruleForm = reactive({
  id: "",
  title: "",
  content: "",
});

const rules = reactive({
  title: [{ required: true, trigger: "blur" }],
  content: [{ required: true, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      console.log("submit!");
      const params = {
        title: ruleForm.title,
        content: ruleForm.content,
      };
      ruleForm.id && (params.id = ruleForm.id);
      const requestFn = ruleForm.id ? editArtcile(params) : addArtcle(params);
      requestFn.then((res) => {
        console.log(res);
        router.push("/posts/index");
      });
    } else {
      console.log("error submit!");
      return false;
    }
  });
};

function getDetail(id) {
  getArticleDetail(id).then((res) => {
    const { title, content } = res.data;
    ruleForm.title = title;
    ruleForm.content = content;
  });
}

onMounted(() => {
  ruleForm.id = route.query.id;
  ruleForm.id && getDetail(ruleForm.id);
});

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
